var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();

/*
 * Authentication token variables
 */
var WCToken;
var WCTrustedToken;
/*
 * constants
 */
var state;
var STATE_TICKER = "TICKER";
var STATE_PDP = "PDP";
var STATE_CART = "CART";
var KEY_LEFT = "LEFT";
var KEY_RIGHT = "RIGHT";
var hostip="192.168.106.129";
var currentProductIndex=0;
var productDescriptionJson;

function authenticateUser(){
	$.ajax({
		url : "https://"+hostip+"/wcs/resources/store/10151/loginidentity",
		contentType : "application/json",
		dataType:"JSON",
		async: false,
		type : "POST",
		data : "{'logonId' : 'testjan','logonPassword' : 'test1234'}",
		success : function(data) {
			alert("Trusted Token"+data.WCTrustedToken);
			WCTrustedToken = data.WCTrustedToken;
			WCToken=data.WCToken;
			
		},
		error : function(err) {
			alert("Failed To Authenticate User");
		}
	});
}

function getCart(){
			alert("getting cart");
			authenticateUser();
			$.ajax({
				contentType : "application/json",
				type : "GET",
				async:false,
				beforeSend : function(request) {
					request.setRequestHeader('WCToken', WCToken);
				},
				url: "http://"+hostip+"/wcs/resources/store/10151/cart/@self",
				success : function(data){
					alert(data);
					alert(data.orderItem[0].orderItemId);
					alert("grandTotal="+data.grandTotal);
					var grandTotal = data.grandTotal.slice(0,-3);
					alert("grandTotalCurrency="+data.grandTotalCurrency);
					var grandTotalCurrency = data.grandTotalCurrency
					$('#paymentAmount').html("<div class='grandTotal'> Total = " + grandTotal +"  "+ grandTotalCurrency + "</div>");
					$('#paymentAmount').addClass('paymentAmountBox');
					for(var i=0;i<data.orderItem.length;i++){
						var item=data.orderItem[i];
						var productUrl=item.productUrl;
						alert(productUrl);
						$.ajax({
							url : productUrl,
							contentType : "application/json",
							type : "GET",
							async: false,
							success : function(data) {
								alert(data.CatalogEntryView[0].name);
								alert(data.CatalogEntryView[0].thumbnail);
								alert(data.CatalogEntryView[0].shortDescription);
								alert(item.orderItemPrice);
								src="http://"+hostip+""+data.CatalogEntryView[0].thumbnail;
								var t = item.orderItemPrice.slice(0,-3);
								$('#list_cart').append('<div class="item"><div class="item_thumbnail"><img src="'+src+'" width="50px" height="50px"></div><div class="item_details"><div class="item_title">'+data.CatalogEntryView[0].name+'</div><div class="item_desc"> Quantity : '+item.quantity+'</div></div><div class="item_price">'+t+' '+grandTotalCurrency+'</div></div>');
							},
							error: function(data){
								alert("error");
							
							}
						});
							
					}
					/*alert(data);
					alert(data.orderItem[0].orderItemId);
					alert(data.orderItem[0].orderItemPrice);
					alert(data.orderItem[0].productUrl);*/

				},
				error: function(){
					alert("Failure");
				}
			});
	
}
function checkout(){
	var orderId;
	$.ajax({
		contentType : "application/json",
		type : "GET",
		async:false,
		beforeSend : function(request) {
			request.setRequestHeader('WCToken', WCToken);
		},
		url: "http://"+hostip+"/wcs/resources/store/10151/cart/@self",
		success : function(data){
		orderId=data.orderId;
		$.ajax({
			url : "https://"+hostip+"/wcs/resources/store/10101/cart/@self/precheckout",
			contentType : "application/json",
			type : "PUT",
			async:false,
			data:"{'orderId' : '"+orderId+"'}",
			beforeSend : function(request) {
				request.setRequestHeader('WCToken',WCToken);
				request.setRequestHeader('WCTrustedToken',WCTrustedToken);

				//request.setRequestHeader('Origin', '*');
			},
			success : function(json) {
				$.ajax({
					url : "https://"+hostip+"/wcs/resources/store/10101/cart/@self/checkout",
					contentType : "application/json",
					type : "POST",
					async:false,
					data:"{'orderId' : '"+orderId+"'}",
					beforeSend : function(request) {
						request.setRequestHeader('WCToken',WCToken);
						request.setRequestHeader('WCTrustedToken',WCTrustedToken);

						//request.setRequestHeader('Origin', '*');
					},
					success : function(json) {
					alert("successfully checked out");
					
					},
					error : function(err) {
						console.log("Error in checking out");
					}
				});	
			
			},
			error : function(err) {
				console.log("Error in pre checkout");
			}
		});	
		},
		error: function(){
			alert("error in trying to get the cart :( ");
		}
	});
	
}
function logout(){
	alert("trying to logout");
	$.ajax({
		url : "https://"+hostip+"/wcs/resources/store/10151/loginidentity/@self",
		contentType : "application/json",
		type : "DELETE",
		beforeSend : function(request) {
			request.setRequestHeader('WCToken', WCToken);
			request.setRequestHeader('WCTrustedToken',WCTrust);
		},
		success : function(data) {
			alert("logged out");
		},
		error: function(data){
			alert("error");
		
		}
	});
		
}
function getShippingInfo(){
	authenticateUser();
	$.ajax({
		url : "https://"+hostip+"/wcs/resources/store/10151/person/@self",
		contentType : "application/json",
		type : "GET",
		async:false,
		beforeSend : function(request) {
			request.setRequestHeader('WCToken',WCToken);
			request.setRequestHeader('WCTrustedToken',WCTrustedToken);

			//request.setRequestHeader('Origin', '*');
		},
		success : function(json) {
			alert("gotcha");
			var newAddress='';
			
			newAddress = newAddress + '<div id="address">';
			
			newAddress = newAddress + '<div class="name">'+'Mr.'+json.lastName+','+'</div>';
			
			alert(json.firstName);
			alert(json.lastName);
			
			newAddress = newAddress +  '<div class="addressLine">';
			for(var x=0;x<json.addressLine.length;x++)
				{
				alert(json.addressLine[x]);
				newAddress = newAddress +  json.addressLine[x]+' ';
				}
			newAddress = newAddress +  '</div>';
			
			newAddress = newAddress +  '<div class="cityname">'+json.city+',</div>';
			newAddress = newAddress +  '<div class="statename">'+json.state+',</div>';
			newAddress = newAddress +  '<div class="countryname">'+json.country+'</div>';
			
			newAddress = newAddress +  '</div>';
			alert("address="+newAddress);
			$('#addressList').append(newAddress);
			$('#address').addClass('addressBox');
			
			alert(json.city);
			alert(json.state);
			alert(json.country);
			
		},
		error : function(err) {
			console.log("Error" + err);
		}
	});	
	
}

function populateTicker(){
	$.ajax({
		url: "http://"+hostip+"/wcs/resources/store/10151/productview/bySearchTerm/vegetables?responseFormat=JSON",
		async:false,
		success : function(data){
			
			productDescriptionJson = data;
			showTicker();
			var ticker = document.getElementById("ticker_product_description");
			ticker.innerHTML=productDescriptionJson.CatalogEntryView[0].name;
			var img=document.getElementById("img_thumbnail_1");
			img.src="http://"+hostip+""+productDescriptionJson.CatalogEntryView[0].thumbnail;
			alert("Ticker Populate Successful");
			
		},
		failure: function(){
			alert("Ticker Populate Failed");
		}
	});
}

function buynow(){
	authenticateUser();
	alert("Inside addtoCart() ");
	var productId = productDescriptionJson.CatalogEntryView[currentProductIndex].uniqueID;
	alert("productID:"+productId);
	$.ajax({
		contentType : "application/json",
		type : "POST",
		async:false,
		beforeSend : function(request) {
			request.setRequestHeader('WCToken', WCToken);
		},
		data:"{'orderItem':[{'productId': '"+productId+"','quantity': '1.0'}]}",
		url: "http://"+hostip+"/wcs/resources/store/10151/cart",
		success : function(data){
			alert("order placed");
			$('#container').hide();
			getCart();
			getShippingInfo();
			$('#addtocart_container').show();
			state = STATE_CART;
			checkout();
		},
		failure: function(){
			alert("I failed");
		}
	});
	
}

function addToWishList(){
	
	$.ajax({
		contentType : "application/json",
		type : "PUT",
		beforeSend : function(request) {
			request.setRequestHeader('WCToken', WCToken);
			request.setRequestHeader('WCTrustedToken',WCTrustedToken);

			//request.setRequestHeader('Origin', '*');
		},	
		data:"{'item': [{'productId' : '10824','quantityRequested' : '2.0'}]}",
		url: "https://"+hostip+"/wcs/resources/store/10151/wishlist/12001?addItem=true",
		success : function(data){
			alert("Added to Wishlist");
		},
		error: function(){
			alert("Adding to Wishlist failed");
		}
	});
	
}
/*
 * renders the PDP details
 */
function renderPDP(){
	var product = document.getElementById("product_description");
	product.innerHTML=productDescriptionJson.CatalogEntryView[currentProductIndex].longDescription;
	var img=document.getElementById("image_big");
	img.src="http://"+hostip+""+productDescriptionJson.CatalogEntryView[currentProductIndex].fullImage;
	var price = $('#product_price');
	alert("Price..................."+productDescriptionJson.CatalogEntryView[currentProductIndex].Price[0].priceValue);
	price.text("$ "+productDescriptionJson.CatalogEntryView[currentProductIndex].Price[0].priceValue);
}

/*
 * changes the contents of the PDP (Product browsing)
 */
function changePDPContents(key){
	var productArraySize = productDescriptionJson.CatalogEntryView.length;
	alert("Array Size:"+productArraySize);
	if(key == KEY_LEFT){
		if(currentProductIndex!=0){
			currentProductIndex--;
			renderPDP();
		}
	}
	else if(key == KEY_RIGHT){
		if(currentProductIndex!=productArraySize-1){
			currentProductIndex++;
			renderPDP();
		}
	}
	
}

function createFile(){
	var fileSystemObj = new FileSystem();
	var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'w');
	    fileObj.writeAll('Line 1');
	    fileObj.writeAll('Line 2');
	    fileObj.writeAll('Line 3');
	    fileSystemObj.closeCommonFile(fileObj);

	
	var fileSystemObj = new FileSystem();
	var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'r+');
	var strLine = '';
	var arrResult = new Array();

	while (strLine = fileObj.readLine()) {
	    arrResult.push(strLine);
	}
	alert(arrResult);

}

function getPaymentInfo(){
	$.ajax({
		contentType : "application/json",
		type : "GET",
		beforeSend : function(request) {
			request.setRequestHeader('WCToken', WCToken);
			request.setRequestHeader('WCTrustedToken',WCTrustedToken);
		},	
		url: "https://192.168.187.129/wcs/resources/store/10151/cart/@self/payment_instruction",
		success : function(data){
			alert("Retrieving payment info successful");
			alert(data);
			alert(data.resourceName);
			alert(data.paymentInstruction[0].length);
			
		},
		error: function(){
			alert("Retrieving payment info failed");
		}
	});
}
var Main =
{

};

Main.onLoad = function()
{
	$('#videoPanel').addClass('videoBigPanel');
	//$('#ticker').hide();
	// Enable key event processing
	
	this.enableKeys();
	alert("depi :"+ this.toString());
	widgetAPI.sendReadyEvent();
	convertDialog();
	$('#rightpane').hide();
	$('#bottomPane').hide();
	$('#addtocart_container').hide();
	populateTicker();
	state = STATE_TICKER;
	alert("on load state:" +state);
	createFile();
	
};

Main.onUnload = function()
{

};

Main.enableKeys = function()
{
	document.getElementById("anchor").focus();
};

Main.keyDown = function()
{
	var keyCode = event.keyCode;
	alert("Key pressed: " + keyCode);

	switch(keyCode)
	{
		case tvKey.KEY_RETURN:
		case tvKey.KEY_PANEL_RETURN:
			alert("RETURN");
			//widgetAPI.sendReturnEvent();
			break;
		case tvKey.KEY_LEFT:
			alert("LEFT");
			if(state == STATE_PDP)
				changePDPContents(KEY_LEFT);
			break;
		case tvKey.KEY_RIGHT:
			alert("RIGHT");
			if(state == STATE_PDP)
				changePDPContents(KEY_RIGHT);
			break;
		case tvKey.KEY_UP:
			alert("UP");
			//addToWishList();
			break;
		case tvKey.KEY_DOWN:
			alert("DOWN");
			//getPaymentInfo();
			break;
		case tvKey.KEY_ENTER:
		case tvKey.KEY_PANEL_ENTER:
			alert("ENTER");
			alert(state);
			if(state == STATE_TICKER)
				resizeWindow();
				state = STATE_PDP;
				alert(state);
			break;
		case 108:
			if(state == STATE_PDP)
				backtovideo();
			break;
		case 22:
			if(state == STATE_PDP)
				buynow();
			break;
		case 21:
			if(state == STATE_PDP)
				addtocart();
			break;
		case 20:
			if(state == STATE_PDP)
				closeDialog();
			break;
		default:
			alert("Unhandled key");
			break;
	}
};

function showTicker(){
	$('#ticker').show();
}

/*
 * resizing the TV screen and displaying the PDP
 */
function resizeWindow(){
	
	renderPDP();
	$('#videoPanel').removeClass('videoBigPanel');
	$('#videoPanel').addClass('videoSmallPanel');
	$('#ticker').hide();
	$('#rightpane').show();
	$('#rightpane').addClass('rightPaneDisplayed');
	$('#bottomPane').show();
}

function backtovideo(){
	$('#videoPanel').removeClass('videoSmallPanel');
	$('#rightpane').hide();
	$('#rightpane').removeClass('rightPaneDisplayed');
	$('#bottomPane').hide();
	$('#videoPanel').addClass('videoBigPanel');
}

function addtocart(){
		authenticateUser();
		alert("Inside addtoCart() ");
		var productId = productDescriptionJson.CatalogEntryView[currentProductIndex].uniqueID;
		alert("productID:"+productId);
		$.ajax({
			contentType : "application/json",
			type : "POST",
			async:false,
			beforeSend : function(request) {
				request.setRequestHeader('WCToken', WCToken);
			},
			data:"{'orderItem':[{'productId': '"+productId+"','quantity': '1.0'}]}",
			url: "http://"+hostip+"/wcs/resources/store/10151/cart",
			success : function(data){
				alert("order placed in addtocart alone.");
				$( "#dialog-confirm" ).dialog( "open" );
				$("#anchor1").focus();
				$(".ui-button").style('color', 'blue', 'important');
			},
			failure: function(){
				alert("I failed");
			}
		});
		
	
}

function convertDialog(){
	$( "#dialog-confirm" ).dialog({
	      resizable: false,
	      height:200,
	      width:400,
	      modal: true,
	      autoOpen: false,
	      show: {
	        effect: "blind",
	        duration: 500
	      },
	      hide: {
	    	  effect: "explode",
		      duration: 500 
	      },
	      buttons: [
	                {
	                    text: " Press 'B' ",
	                    "class": 'BButtonClass',
	                    click: function() {
	                        // Cancel code here
	                    }
	                }
	            ],
	      
	    });
}

function closeDialog(){
	if(state == STATE_PDP){
		resizeWindow();
		alert("gg: "+state);
	}
		
	$( "#dialog-confirm" ).dialog( "close" );
	$("#anchor").focus();

	
}